package com.jacobson.huobi.utils

import android.content.Context
import android.media.AudioFocusRequest
import android.media.AudioManager
import android.os.Build
import androidx.annotation.NonNull
import com.jacobson.core.framework.delegation.WeakRef
import com.jacobson.core.widget.ToastUtil
import com.jacobson.core.widget.logger.LoggerFactory
import com.jacobson.huobi.HuobiApplication
import com.tencent.qcloudtts.RealtimeTTS.RealtimeTtsController
import com.tencent.qcloudtts.VoiceLanguage
import com.tencent.qcloudtts.VoiceSpeed
import com.tencent.qcloudtts.VoiceType
import com.tencent.qcloudtts.VoiceVolume
import com.tencent.qcloudtts.callback.QCloudPlayerCallback

/** 语音帮助类 */
object TTSHelper {
    private val logger = LoggerFactory.getLogger(TTSHelper::class.java)
    private var ttsController: RealtimeTtsController? = null
    fun startTTS(data: String) {
        logger.i("start TTS： $data")
        fetchTts().run {
//            this.setVoiceVolume(VoiceVolume.VOICE_VOLUME_FIVE.num)
            startTts(data, { ttsException ->
                ToastUtil.toast(HuobiApplication.getInstance(), "语音播放异常 >>> ${ttsException.errMsg}")
            }, object : QCloudPlayerCallback {
                override fun onTTSPlayStart() {
                }

                override fun onTTSPlayWait() {
                }

                override fun onTTSPlayNext() {
                }

                override fun onTTSPlayStop() {
                }

                override fun onTTSPlayEnd() {
                }

                override fun onTTSPlayResume() {
                }

            })
        }
    }

    @Synchronized
    private fun fetchTts(): RealtimeTtsController {
        if (ttsController == null) {
            val ttsControllerDelegate by WeakRef {
                RealtimeTtsController().apply {
                    this.init(1253579779, "AKID64pRq2qnMhqnX4sdaHjuqZ2FDvNcQEer", "76xa1BAuWu68wVqwnSwDGLI4cv1xe7LM")
                    this.setProjectId(1172338)
                    this.setVoiceSpeed(VoiceSpeed.VOICE_SPEED_NORMAL.num)
                    this.setVoiceType(VoiceType.VOICE_TYPE_AFFNITY_FEMALE.num)
                    this.setVoiceLanguage(VoiceLanguage.VOICE_LANGUAGE_CHINESE.num)
                    requestAudioFocus(HuobiApplication.getInstance(), this)
                }
            }
            ttsController = ttsControllerDelegate
        }
        return ttsController!!
    }

    private fun requestAudioFocus(@NonNull context: Context, @NonNull ttsController: RealtimeTtsController) {
        val listener = AudioManager.OnAudioFocusChangeListener { focusChange ->
            when (focusChange) {
                AudioManager.AUDIOFOCUS_LOSS -> //丢失焦点，直接
                    ttsController.stop()
                AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {
                    //丢失焦点，但是马上又能恢复
                }
                AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> {
                    //降低音量
                }
                AudioManager.AUDIOFOCUS_GAIN -> {
                    //获得了音频焦点
                }
            }
        }
        val am = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val audioFocusRequest = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
                .setOnAudioFocusChangeListener(listener)
                .build()
            am.requestAudioFocus(audioFocusRequest)
        } else {
            am.requestAudioFocus(listener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN)
        }
    }
}